package net.vinote.smart.platform.module.dbpool;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.PreparedStatement;

class ProxyPreparedStatement implements InvocationHandler {
	private PreparedStatement ps;
	private PreparedStatement proxyPs;
	private ProxyConnection conn;

	private final int flag;

	public ProxyPreparedStatement(ProxyConnection conn, PreparedStatement ps) {
		this.ps = ps;
		this.conn = conn;
		flag = conn.getModifyFlag();

		proxyPs = (PreparedStatement) Proxy.newProxyInstance(ps.getClass()
				.getClassLoader(), new Class[] { PreparedStatement.class },
				this);
	}

	public PreparedStatement preparedStatement() {
		return proxyPs;
	}

	@Override
	public Object invoke(Object proxy, Method method, Object[] args)
			throws Throwable {
		if (flag == conn.getModifyFlag()) {
			conn.updateAccessTime();
			return method.invoke(ps, args);
		}
		// 当前ps关联的connection对象已失效
		else {
			ps.close();
			if (!"close".equals(method.getName())) {
				throw new RuntimeException("Connection has already disabled");
			}
			return null;
		}
	}
}
